package com.walk.zworld.module.fragment

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.os.Handler
import android.view.Gravity
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.walk.zworld.R
import com.walk.zworld.databinding.FragmentDialogMainBinding
import com.walk.zworld.module.me.viewmodel.MainMeViewModel
import com.base.lib.base.adapter.BaseSkeletonAdapter
import com.base.lib.base.utils.ToastUtil.showToastCenter
import com.base.lib.base.view.BaseMvvmViewBindingFragment
import com.base.lib.base.widget.PaintView
import com.base.lib.xdialog.anno.DialogPosition
import com.base.lib.xdialog.anno.DialogStyle
import com.base.lib.xdialog.anno.EmptyViewState
import com.base.lib.xdialog.anno.LoadingStyle
import com.base.lib.xdialog.bean.AddressSelectLevel.Companion.LEVEL_AREA
import com.base.lib.xdialog.bean.textStyle
import com.base.lib.xdialog.components.*
import com.base.lib.xdialog.dialog.BlurEngine
import com.base.lib.xdialog.dialog.content.*
import com.base.lib.xdialog.dialog.createDialog
import com.base.lib.xdialog.dialog.showDialog
import com.base.lib.xdialog.rv.emptyView
import com.base.lib.xdialog.text.NormalTextView
import com.base.lib.xdialog.utils.DialogUtils.getDrawable
import com.base.lib.xdialog.utils.DialogUtils.getScreenHeight
import com.base.lib.xdialog.utils.Utils
import com.base.lib.xdialog.utils.drawableOf
import com.base.lib.xdialog.utils.onDebouncedClick

/**
 * Describe:
 * 首页，使用了ViewBinding示例
 *
 */
class MainDialogFragment : BaseMvvmViewBindingFragment<FragmentDialogMainBinding, MainMeViewModel>() {

    companion object {
        fun newsInstance(): MainDialogFragment {
            return MainDialogFragment()
        }
    }


    override fun onBindLayout(): Int = R.layout.fragment_dialog_main

    override fun onBindingClass(): Class<FragmentDialogMainBinding> {
        return FragmentDialogMainBinding::class.java
    }

    override fun initView(mView: View) {
    }

    override fun initData() {
        doCreateView()
    }

    override fun initListener() {
    }

    override fun onBindViewModel(): Class<MainMeViewModel> {
        return MainMeViewModel::class.java
    }

    override fun initViewObservable() {
    }

    private var customList: CustomList? = null
    private var draggable: Boolean = false

    private fun doCreateView() {
        val activity = requireActivity()
        val supportFragmentManager = activity.supportFragmentManager
        val builder = createDialogBuilder()
        val binding1 = requireBinding()
        binding1.sw.setOnCheckedChangeListener { _, isChecked ->
            draggable = isChecked
        }
        binding1.btnNoBg.setOnClickListener {
            showDialog(activity,"normal") {
                withBottomSheet(draggable)
                withStyle(DialogStyle.STYLE_WRAP)
                withContent(UpgradeContent())
                withDialogBackground(null)
                onDismiss { showToastCenter("Dismissed") }
                onShow { showToastCenter("Showed") }
            }
        }
        binding1.btnNoBgOneThird.onDebouncedClick {
            builder.withBottomSheet(draggable)
            builder.withStyle(DialogStyle.STYLE_TWO_THIRD)
            builder.build().show(supportFragmentManager, "normal")
        }
        binding1.btnNoBgHalf.onDebouncedClick {
            builder.withBottomSheet(draggable)
            builder.withStyle(DialogStyle.STYLE_HALF)
            builder.build().show(supportFragmentManager, "normal")
        }
        binding1.btnBlurBg.onDebouncedClick {
            showDialog(activity,"normal") {
                withBottomSheet(draggable)
                withStyle(DialogStyle.STYLE_WRAP)
                withNoAnimation(true)
                withBlurBackground(BlurEngine.BlurEffect().apply {
                    this.enable = true
                })
                withContent(UpgradeContent())
                withDialogBackground(null)
                onDismiss { showToastCenter("Dismissed") }
                onShow { showToastCenter("Showed") }
            }
        }
        binding1.btnNormal.setOnClickListener {
            showDialog(activity,"normal") {
                withBottomSheet(draggable)
                withStyle(DialogStyle.STYLE_WRAP)
                withTitle(red18fTitle("测试标题 [RED|18f]"))
                withContent(MultipleContent())
                withBottom(singleOk())
            }
        }
        onDebouncedClick(binding1.btnNormalTop) {
            createDialog {
                withBottomSheet(draggable)
                withPosition(DialogPosition.POS_TOP)
                withTitle(boldLeftTitle("测试标题 [BOLD|LEFT]"))
                withContent(object: IDialogContent {
                    override fun getView(ctx: Context): View {
                        return PaintView(ctx)
                    }
                })
            }.show(supportFragmentManager, "normal_top")
        }
        onDebouncedClick(binding1.btnNormalBottom) {
            createDialog {
                withBottomSheet(draggable)
                darkMode(true)
                withPosition(DialogPosition.POS_BOTTOM)
                withTitle(simpleTitle("测试标题 [WHITE]"))
                withContent(MultipleContent())
                withBottom(leftMiddleRightFooter())
            }.show(supportFragmentManager, "normal_bottom")
        }
        onDebouncedClick(binding1.btnEditorNormal) {
            // The DSL styled way to create dialog.
            showDialog(activity,"editor") {
                withBottomSheet(draggable)
                withStyle(DialogStyle.STYLE_HALF)
                withDialogCornerRadius(8)
                withTitle(simpleTitle("普通编辑对话框 [无限制]"))
                withContent(simpleEditor {
                    withClearDrawable(
                        drawableOf(R.drawable.ic_baseline_cancel_24)
                    )
                })
                withBottom(leftMiddleRightFooterWhite())
            }
        }
        binding1.btnEditorNumeric.setOnClickListener {
            showDialog(activity,"editor") {
                withBottomSheet(draggable)
                withStyle(DialogStyle.STYLE_TWO_THIRD)
                withTitle(simpleTitle("编辑对话框（数字|单行|长度10）"))
                withContent(simpleEditor {
                    withSingleLine(true)
                    withNumeric(true)
                    withContent("10086")
                    withHint("在这里输入数字...")
                    withBottomLineColor(Color.LTGRAY)
                    withMaxLength(10)
                })
                withBottom(confirmCancel())
            }
        }
        binding1.btnListNormal.onDebouncedClick {
            showDialog(activity) {
                withBottomSheet(draggable)
                withPosition(DialogPosition.POS_BOTTOM)
                withTitle(simpleTitle("简单的列表"))
                withContent(simpleList {
                    withTextStyle(textStyle {
                        withColor(Color.BLACK)
                        withSize(16f)
                        withTypeFace(Typeface.BOLD)
                        withGravity(Gravity.CENTER)
                    })
                    withShowIcon(true)
                    withList(Utils.getSimpleListData())
                    onItemSelected { dialog, item ->
                        showToastCenter("${item.id} : ${item.content}")
                        dialog.dismiss()
                    }
                })
            }
        }
        binding1.btnAddress.onDebouncedClick {
            showDialog(activity,"list") {
                withBottomSheet(draggable)
                withPosition(DialogPosition.POS_BOTTOM)
                withMargin(8)
                withTitle(simpleTitle("地址对话框"))
                withContent(addressContent {
                    withLevel(LEVEL_AREA)
                    onSelected { dialog, province, city, area ->
                        showToastCenter("$province - $city - $area")
                        dialog.dismiss()
                    }
                })
            }
        }
        binding1.btnContent.onDebouncedClick {
            showDialog(activity,"list") {
                withBottomSheet(draggable)
                withStyle(DialogStyle.STYLE_TWO_THIRD)
                withPosition(DialogPosition.POS_BOTTOM)
                outCancelable(true)
                withTitle(simpleTitle("简单内容对话框"))
                withContent(simpleContent {
                    withContent("君不見黃河之水天上來，奔流到海不復回。\n" +
                            "        君不見高堂明鏡悲白髮，朝如青絲暮成雪。\n" +
                            "        人生得意須盡歡，莫使金樽空對月。\n" +
                            "        天生我材必有用，千金散盡還復來。\n" +
                            "        烹羊宰牛且爲樂，會須一飲三百杯。\n" +
                            "        岑夫子，丹丘生。將進酒，杯莫停。\n" +
                            "        與君歌一曲，請君爲我側耳聽。\n" +
                            "        鐘鼓饌玉不足貴，但願長醉不願醒。\n" +
                            "        古來聖賢皆寂寞，惟有飲者留其名。\n" +
                            "        陳王昔時宴平樂，斗酒十千恣讙謔。\n" +
                            "        主人何為言少錢？徑須沽取對君酌。\n" +
                            "        五花馬，千金裘。呼兒將出換美酒，與爾同銷萬古愁。")
                })
            }
        }
        binding1.btnCustomList.onDebouncedClick { showCustomListDialog() }
        binding1.btnNotCancelable.onDebouncedClick {
            showDialog(activity,"not cancelable") {
                withBottomSheet(draggable)
                withStyle(DialogStyle.STYLE_WRAP)
                outCancelable(false)
                backCancelable(false)
                withDialogBackground(null)
                withContent(UpgradeContent())
            }
        }
        binding1.btnSimpleGrid.onDebouncedClick {
            showDialog(activity,"grid") {
                withBottomSheet(draggable)
                withMargin(0)
                withPosition(DialogPosition.POS_BOTTOM)
                withTitle(simpleTitle("简单的网格"))
                withContent(simpleGrid<Int> {
                    withLayout(R.layout.item_tool_color)
                    withSpanCount(5)
                    onBind { helper, item ->
                        helper.getView<AppCompatImageView>(R.id.iv).setImageDrawable(getDrawable(item, 5f))
                    }
                    onItemSelected { dialog, item ->
                        showToastCenter("$item")
                        dialog.dismiss()
                    }
                    withList(Utils.getSimpleGridData())
                })
            }
        }
        binding1.btnBottomSheet.onDebouncedClick {
            showDialog(activity) {
                withBottomSheet(true)
                withFullscreen(true)
                withFitToContents(false)
                withPeekHeight(200)
                withHalfExpandedRatio(.65f)
                withMargin(0)
                withPosition(DialogPosition.POS_BOTTOM)
                withTitle(simpleTitle("简单的网格"))
                withContent(simpleGrid<Int> {
                    withLayout(R.layout.item_tool_color)
                    withSpanCount(5)
                    onBind { helper, item ->
                        helper.getView<AppCompatImageView>(R.id.iv).setImageDrawable(getDrawable(item, 5f))
                    }
                    onItemSelected { dialog, item ->
                        showToastCenter("$item")
                        dialog.dismiss()
                    }
                    withList(Utils.getSimpleGridData())
                })
            }
        }
    }

    private fun showCustomListDialog() {
        val adapter = object : BaseSkeletonAdapter<SimpleList.Item, BaseViewHolder>(R.layout.uix_dialog_content_list_simple_item) {
            override fun convert(holder: BaseViewHolder, item: SimpleList.Item) {
                val tv = holder.getView<NormalTextView>(R.id.tv)
                tv.text = item.content
                item.gravity?.let { tv.gravity = it }
                item.icon?.let { holder.setImageDrawable(R.id.iv, it) }
            }
        }
        adapter.setOnItemClickListener { adapter, _, position ->
            val item = adapter.data[position] as SimpleList.Item
            showToastCenter("${item.id} : ${item.content}")
            customList?.getDialog()?.dismiss()
        }
        customList = customList {
            withAdapter(adapter)
            withEmptyView(emptyView(requireActivity()) {
                withStyle(LoadingStyle.STYLE_IOS)
                withState(EmptyViewState.STATE_LOADING)
                withLoadingTips("加载中…")
                withLoadingTipsColor(Color.BLUE)
            })
        }
        createDialog {
            withBottomSheet(draggable)
            withPosition(DialogPosition.POS_BOTTOM)
            withHeight(getScreenHeight() / 2)
            outCancelable(true)
            withTitle(simpleTitle("自定义列表对话框"))
            withContent(customList!!)
        }.show(requireActivity().supportFragmentManager, "custom-list")
        // 先显示对话框再加载数据的情形
        Handler().postDelayed({
            customList?.hideEmptyView()
            adapter.setList(Utils.getCustomListData())
        }, 3000)
    }

    private fun createDialogBuilder(): com.base.lib.xdialog.dialog.BeautyDialog.Builder {
        val builder = com.base.lib.xdialog.dialog.BeautyDialog.Builder()
        builder.darkMode(true)
        builder.withPosition(DialogPosition.POS_BOTTOM)
        builder.withContent(MultipleContent())
        builder.withTitle(whiteSimpleTitle("测试标题 [WHITE]"))
        builder.withBottom(leftMiddleRightFooter())
        return builder
    }
}
